<?php
//在任何HTML输出之前开启会话
session_start();
include_once 'jwt.php';
/*
$token = urldecode($_SERVER['HTTP_TOKEN']); //读取自定义header信息
if($token){
    $username = urldecode($_SERVER['HTTP_USERNAME']); //读取自定义header信息
    //使用jwt进行签名验证
}
else{
    //说明没有带签名
}*/

$username = trim($_POST['username']); //使用POST全局数组获取前端表单提交的数据
$pw = trim($_POST['password']);
$rememberMe = $_POST['rememberMe'];
//进行必要的数据验证
$a = array();
if(!strlen($username) || !strlen($pw)){
    $a['code'] = -1;
    $a['msg'] = '用户名和密码都必须要填写';
    echo json_encode($a);
    exit;
}

include_once "conn.php";
$data = new Bbs();
$pw = md5($pw);
$result = $data->login($username,$pw);
$expires = time()+3600*24*7;  //保存登录状态维持一周
if($result['code'] == '-1'){
    $_SESSION['loggedUserID'] = '';
    $_SESSION['loggedUsername'] = '';
    $_SESSION['isAdmin'] = '';
}
else{
    //登录成功，生成token
    $payload_test = array('loggedUserID'=>$result['data']['id'],'iat' => time(), 'exp' => time() + 7200, 'nbf' => time(),  'jti' => md5(uniqid('JWT', true) . time()));;
    $token = Jwt::getToken($payload_test);
    $result['token'] = $token;
    $_SESSION['loggedUserID'] = $result['data']['id'];
    $_SESSION['loggedUsername'] =  $result['data']['username'];
    $_SESSION['isAdmin'] =  $result['data']['admin'];
    //判断一下是否要保存登录状态
    if($rememberMe == 1){
        //说明要保存登录状态
        setcookie('rememberMe',1,$expires);
        setcookie('username',$username,$expires);
    }
    else{
        //说明要取消保存状态
        setcookie('rememberMe','',time()-3600);
        setcookie('username','',time()-3600);
    }
}

echo json_encode($result);